from django.utils import timezone
from product.models import ProductsInventory, ProductsInventorySnapshot

class ProductInventorySnapshotService:
    """商品库存快照服务"""
    
    def create_daily_snapshot(self, snapshot_date=None):
        """
        创建每日商品库存快照
        将当前商品库存数据保存到快照表中
        
        Args:
            snapshot_date: datetime.date, 快照日期，如果为None则使用当前日期
        """
        # 获取所有商品库存记录
        inventories = ProductsInventory.objects.all()
        
        # 如果没有传入日期，则使用当前日期
        if snapshot_date is None:
            snapshot_date = timezone.localtime().date()
        
        # 创建快照记录列表
        snapshots = []
        for inventory in inventories:
            snapshot = ProductsInventorySnapshot(
                product_code=inventory.product_code,
                instock_quantity=inventory.instock_quantity,
                delivery_quantity=inventory.delivery_quantity,
                inventory_date=snapshot_date
            )
            snapshots.append(snapshot)
            
        # 批量创建快照
        ProductsInventorySnapshot.objects.bulk_create(snapshots)
        
        return snapshots
